package com.likeyoudo.views.activity.public_service;


import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.Nullable;

import com.alibaba.fastjson2.JSON;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.likeyoudo.common.BaseActivity;
import com.likeyoudo.common.msg.MsgEvent;
import com.likeyoudo.views.R;
import com.likeyoudo.views.activity.FilePreViewActivity;
import com.likeyoudo.views.activity.ImagePreviewActivity;
import com.likeyoudo.views.api.xg.ApprovalApi;
import com.likeyoudo.views.constants.xg.ApprovalConstants;
import com.likeyoudo.views.databinding.ActivityPublicApprovalFormBinding;
import com.likeyoudo.views.type.entity.xg.Approval;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.hutool.core.util.StrUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class PublicApprovalActivity extends BaseActivity {

    ActivityPublicApprovalFormBinding binding;
    Approval approval;

    ApprovalApi approvalApi;

    EditText applicationYear, applicationUserId, applicationUserName, applicationService, applicationScore, applicationContent, applicationDescription, approvalRefuse;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_public_approval_form;
    }

    ;

    @Nullable
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPublicApprovalFormBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        getAllView();
        initView();
    }

    private void initView() {
        setImmersiveWindows();
        showBackButton();
        setTitle("审批详情");


        Intent intent = getIntent();
        String data = intent.getStringExtra(ApprovalConstants.DATA_KEY);
        if (StrUtil.isBlank(data)) {
            return;
        }
        approval = JSON.toJavaObject(data, Approval.class);
        setAllView();
        showAndHidePicsORFile();


    }

    ;

    private void getAllView() {
        applicationYear = findViewById(R.id.approval_form_application_year);
        applicationUserId = findViewById(R.id.approval_form_application_user_id);
        applicationUserName = findViewById(R.id.approval_form_application_user_name);
        applicationService = findViewById(R.id.approval_form_application_service);
        applicationScore = findViewById(R.id.approval_form_application_score);
        applicationContent = findViewById(R.id.approval_form_application_content);
        applicationDescription = findViewById(R.id.approval_form_application_description);


        approvalApi = new ApprovalApi();
    }


    private void setAllView() {
        applicationYear.setText(approval.getApprovalYear() + "");
        applicationUserId.setText(approval.getUserId() + "");
        applicationUserName.setText(approval.getNickName() + "");
        applicationService.setText(approval.getName() + "");
        applicationScore.setText(approval.getScore() + "");
        applicationContent.setText(approval.getContent() + "");
        applicationDescription.setText(approval.getDescription() + "");
    }

    // 申请分值和申请描述校验
    private Boolean getViewAndRef() {
        if (applicationScore.getText() == null || "".equals(applicationScore.getText().toString()) || applicationDescription.getText() == null || "".equals(applicationDescription.getText() + "")) {
            ToastUtils.showShort("内容不能为空");
            return false;
        } else {
            approval.setDescription(applicationDescription.getText().toString());
            if (!RegexUtils.isMatch("^(?!0)\\d{1,3}(\\.\\d)?$", applicationScore.getText())) {
                ToastUtils.showShort("申请分值范围错误,只包含数字且最多有一位小数且不能超过999.9");
                return false;
            }
            approval.setScore(Double.valueOf(applicationScore.getText().toString()));
            return true;
        }
    }

    // 图片和文件表单隐藏情况
    public void showAndHidePicsORFile() {
        if (approval.getPictures() == null || "null".equals(approval.getPictures()) || "".equals(approval.getPictures())) {
            findViewById(R.id.show_pics).setVisibility(View.INVISIBLE);
            findViewById(R.id.title_pics).setVisibility(View.INVISIBLE);
        }

        if (approval.getFiles() == null || "null".equals(approval.getFiles()) || "".equals(approval.getFiles())) {
            findViewById(R.id.show_files).setVisibility(View.INVISIBLE);
            findViewById(R.id.title_files).setVisibility(View.INVISIBLE);
        }
    }

    // 设置查看图片按钮逻辑
    public void showPics(View view) {
        // 设置点击图片按钮逻辑
        if (StrUtil.isNotBlank(approval.getPictures()) && !"null".equals(approval.getPictures())) {
            String[] split = approval.getPictures().split(",");
            if (split.length == 0) {
                ToastUtils.showShort("无图片内容");
            } else {
                // 跳转到预览图片页面
                Intent intent = new Intent(this, ImagePreviewActivity.class);
                intent.putExtra(ApprovalConstants.PICS_KEY, approval.getPictures());
                ActivityUtils.startActivity(intent);
            }
        } else {
            ToastUtils.showShort("无图片内容");
        }
    }

    // 设置查看文件按钮逻辑
    public void showFiles(View view) {
        // 设置点击文件按钮逻辑
        if (StrUtil.isNotBlank(approval.getFiles()) && !"null".equals(approval.getFiles())) {
            String[] split = approval.getFiles().split(",");
            if (split.length == 0) {
                ToastUtils.showShort("无文件内容");
            } else {
                // 跳转到预览文件页面
                Intent intent = new Intent(this, FilePreViewActivity.class);
                intent.putExtra(ApprovalConstants.FILES_KEY, approval.getFiles());
                ActivityUtils.startActivity(intent);
            }
        } else {
            ToastUtils.showShort("无文件内容");
        }
    }

    // 设置点击同意按钮逻辑
    public void approvalPass(View view) {
        // 获取并验证参数
        Boolean ref = getViewAndRef();
        if (ref) {
            // 二次确认
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("您确认通过这条申请吗?")
                    .setPositiveButton("确定", (dialog, which) -> {
                        approval.setState("3");
                        if (StrUtil.isNotBlank(approval.getOpinion())){
                            approval.setOpinion("");
                        }
                        RequestBody approvalBody = RequestBody.create(MediaType.get("application/json; charset=utf-8"), approval.toString());
                        approvalApi.update(approvalBody);
                    })
                    .setNegativeButton("取消", (dialog, which) -> dialog.cancel())
                    .show();
        }
    }

    // 设置点击拒绝按钮逻辑
    public void approvalRefuse(View view) {

        Boolean ref = getViewAndRef();
        if (ref) {
            // 加载自定义布局
            LayoutInflater inflater = LayoutInflater.from(this);
            View refuseView = inflater.inflate(R.layout.form_refuse_input, null);
            approvalRefuse = refuseView.findViewById(R.id.approval_refuse);

            new AlertDialog.Builder(this)
                    .setView(refuseView)
                    .setTitle("请输入拒绝理由")
                    .setPositiveButton("确定", (dialog, which) -> {
                        if (approvalRefuse.getText() == null || approvalRefuse.getText().toString().isEmpty() || "".equals(approvalRefuse.getText().toString())) {
                            ToastUtils.showShort("拒绝理由不能为空");
                            return;
                        }
                        //设置拒绝
                        approval.setState("4");
                        //设置拒绝理由
                        approval.setOpinion(approvalRefuse.getText().toString());
                        RequestBody approvalBody = RequestBody.create(MediaType.get("application/json; charset=utf-8"), JSON.toJSONString(approval));
                        approvalApi.update(approvalBody);

                    })
                    .setNegativeButton("取消", (dialog, which) -> dialog.cancel())
                    .show();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MsgEvent event) {
        String type = event.getType();
        if (approvalApi.updateMsgType().equals(type)) {
            finish();
        }
    }
}